import wx from 'wx'
import Fly from 'flyio'
import appConfig from '@/appConfig'

var fly = new Fly()
import store from '../store'
var qs = require('qs');
//配置请求基地址
;(fly.config.baseURL = appConfig.baseUrl),
  //设置超时
  (fly.config.timeout = 15000)
//跨域请求是否发送第三方cookie
fly.config.timeout = 15000
fly.config.withCredentials = true
  //添加响应拦截器，响应拦截器会在then/catch处理之前执行
  fly.interceptors.request.use(
    (fly, promise) => {
      
      fly.headers['Content-type'] = 'application/x-www-form-urlencoded'
      
      fly.body = qs.stringify(fly.body)

      wx.showLoading({
        title: '加载中'
      })
      const token = wx.getStorageSync('sessionToken')
      if (token) {
        fly.headers['Authorization'] = token // 让每个请求携带自定义token 请根据实际情况自行修改
      }
      return fly
    },
    error => {
      // Do something with request error

      Promise.reject(error)
    }
  )

fly.interceptors.response.use(
  (response, promise) => {
    const res = response.data
    /**
     * code为非0是抛错 可结合自己业务进行修改
     */
    if (res.code !== 0) {
      wx.showToast({
        title: res.message,
        icon: 'none',
        duration: 2 * 1000
      })
      // 1000001:非法的token; -99:Token 过期了;
      if (res.code === 1000001 || res.code === -99) {
        store.dispatch('FedLogOut').then(() => {})
      }
      return promise.reject('error')
    } else {
      wx.hideLoading()
      return promise.resolve(response.data)
    }
  },
  (err, promise) => {
    wx.hideLoading()
    wx.showToast({
      title: err.message,
      icon: 'none'
    })
    return promise.resolve()
  }
)

export default fly
